package com.zhiche.lisa.lspm.service.upload.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.qiniu.http.Response;
import com.qiniu.storage.model.FileInfo;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.qiniu.config.QiniuConfig;
import com.zhiche.lisa.core.utils.qiniu.util.QiniuUtils;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierLicenseAttach;
import com.zhiche.lisa.lspm.dao.model.driver.DriverLicenseAttach;
import com.zhiche.lisa.lspm.dao.model.lsp.LspLicenseAttach;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerLicenseAttach;
import com.zhiche.lisa.lspm.service.carrier.ICarrierLicenseAttachService;
import com.zhiche.lisa.lspm.service.driver.IDriverLicenseAttachService;
import com.zhiche.lisa.lspm.service.lsp.LspLicenseAttachService;
import com.zhiche.lisa.lspm.service.trailer.TrailerLicenseAttachService;
import com.zhiche.lisa.lspm.service.upload.UploadService;
import com.zhiche.lisa.lspm.vo.attach.AttachInfoVO;
import com.zhiche.lisa.lspm.vo.attach.AttachKeyVO;
import com.zhiche.lisa.lspm.vo.common.GetUrlVO;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 上传 service impl
 * @since 2018-06-05
 * @author lbl
 */
@Service
public class UploadServiceImpl implements UploadService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadServiceImpl.class);

    @Autowired
    private QiniuConfig qiniuConfig;

    @Autowired
    private LspLicenseAttachService lspLicenseAttachService;

    @Autowired
    private ICarrierLicenseAttachService carrierLicenseAttachService;

    @Autowired
    private TrailerLicenseAttachService trailerLicenseAttachService;

    @Autowired
    private IDriverLicenseAttachService driverLicenseAttachService;

    @Override
    public String getToken(String key) {
        return QiniuUtils.generateSimpleUploadTicket(qiniuConfig.getBucket(),key);
    }

    @Override
    public GetUrlVO getUrl(String key,String type) {
        GetUrlVO getUrlVO = new GetUrlVO();

        try {

            getUrlVO.setUrl(QiniuUtils.generateDownloadTicket(qiniuConfig.getDownloadUrl(), key));

            //根据key获取附件名称
            String attachName = getAttacName(key,type);
            getUrlVO.setName(attachName);

        } catch (Exception e) {
            LOGGER.error("UploadServiceImpl.getUrl ERROR Message : {} ", e);
        }

        return getUrlVO;
    }

    @Override
    public List<AttachInfoVO> getAttachInfo(AttachKeyVO attachKeyVO) {

        List<AttachInfoVO> attachInfoVOList = new ArrayList<>();

        String[] keys = attachKeyVO.getKeys();

        if(ArrayUtils.isNotEmpty(keys)){

            for (String key : keys) {
                AttachInfoVO attachInfoVO = new AttachInfoVO();

                // 查看地址
                String lookUrl = QiniuUtils.generateDownloadTicket(qiniuConfig.getDownloadUrl(), key);
                attachInfoVO.setLookUrl(lookUrl);

                // 名称
                //根据key获取附件名称
                String attachName = getAttacName(key, attachKeyVO.getType());
                attachInfoVO.setName(attachName);

                // 格式
                try {
                    attachInfoVO.setFormat(QiniuUtils.getType(key));
                } catch (Exception e) {
                    LOGGER.error("获取文件格式异常...", e);
                }

                // 下载地址
                String downloadUrl = lookUrl + "&attname=" + attachName;
                attachInfoVO.setDownloadUrl(downloadUrl);

                // 文件大小
                try {
                    attachInfoVO.setSize(QiniuUtils.getSize(key));
                } catch (Exception e) {
                    LOGGER.error("获取文件大小异常...", e);
                }

                // 文件上传时间
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Long time = QiniuUtils.getPutTime(key);
                    if (time != null) {
                        String timeStr = time.toString().substring(0, 10);
                        attachInfoVO.setUploadTime(simpleDateFormat.format(new Date(Long.valueOf(timeStr + "000"))));
                    }
                } catch (Exception e) {
                    LOGGER.error("获取文件上传时间异常...", e);
                }
                attachInfoVOList.add(attachInfoVO);

            }
        }

        return attachInfoVOList;
    }

    @Override
    public GetUrlVO getUrl(String key,String type,String width,String heigth){
        GetUrlVO getUrlVO = new GetUrlVO();
        try {
            getUrlVO.setUrl(QiniuUtils.generateDownloadTicket(qiniuConfig.getDownloadUrl(), key,"0",width,heigth));
            String attachName = getAttacName(key,type);
            getUrlVO.setName(attachName);
        } catch (Exception e) {
            LOGGER.error("UploadServiceImpl.getUrl ERROR Message : {} ", e);
        }

        return getUrlVO;
    }

    public String getStrUrl(String key){
        String downloadUrl = QiniuUtils.generateDownloadTicket(qiniuConfig.getDownloadUrl(), key);
        return downloadUrl;
    }

    @Override
    public String getStrUrl(String key, String width, String heigth) {
        String downloadUrl = QiniuUtils.generateDownloadTicket(qiniuConfig.getDownloadUrl(), key,"0",width,heigth);
        return downloadUrl;
    }

    @Override
    public void deleteFile(String key) throws BaseException {
        try{
            FileInfo fileInfo = QiniuUtils.getFileInfo(key);
            if(Objects.nonNull(fileInfo)){
                Response response =  QiniuUtils.DeleteFile(key);
                if(Objects.nonNull(response)){
                    int statusCode = response.statusCode;
                    if(statusCode != 200){
                        throw new BaseException(response.error);
                    }
                }
            }
        }
        catch (Exception ex){
            throw new BaseException(ex.getMessage());
        }
    }

    /**
     * 根据key获取附件名
     * @param key
     * @return
     */
    private String getAttacName(String key,String type){

        String attachName = null;

        //查询供应商
        if(type.equals("lsp")){
            //根据key获取附件名称
            EntityWrapper<LspLicenseAttach> ewLA = new EntityWrapper<>();
            ewLA.eq("attach_key",key);
            List<LspLicenseAttach> lspLicenseAttaches = lspLicenseAttachService.selectList(ewLA);
            if(!CollectionUtils.isEmpty(lspLicenseAttaches)){
                attachName = lspLicenseAttaches.get(0).getAttachName();
            }
        }

        //查询牵引车
        if(type.equals("carrier")){
            EntityWrapper<CarrierLicenseAttach> ewCA = new EntityWrapper<>();
            ewCA.eq("attach_key",key);
            List<CarrierLicenseAttach> carrierLicenseAttaches = carrierLicenseAttachService.selectList(ewCA);
            if(!CollectionUtils.isEmpty(carrierLicenseAttaches)){
                attachName = carrierLicenseAttaches.get(0).getAttachName();
            }
        }

        //查询司机
        if(type.equals("driver")){
            EntityWrapper<DriverLicenseAttach> ewDA = new EntityWrapper<>();
            ewDA.eq("attach_key", key);
            List<DriverLicenseAttach> driverLicenseAttaches = driverLicenseAttachService.selectList(ewDA);
            if (!CollectionUtils.isEmpty(driverLicenseAttaches)) {
                attachName = driverLicenseAttaches.get(0).getAttachName();
            }
        }

        //查询挂车
        if(type.equals("trailer")){
            EntityWrapper<TrailerLicenseAttach> ewTA = new EntityWrapper<>();
            ewTA.eq("attach_key", key);
            List<TrailerLicenseAttach> trailerLicenseAttaches = trailerLicenseAttachService.selectList(ewTA);
            if (!CollectionUtils.isEmpty(trailerLicenseAttaches)) {
                attachName = trailerLicenseAttaches.get(0).getAttachName();
            }
        }

        return attachName;
    }
}
